package com.b.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.b.dao.OrderMapper;
import com.b.domain.Address;
import com.b.domain.Order;
import com.b.domain.Product;
import com.b.domain.SeckillActivity;
import com.b.repository.AddressRepository;
import com.b.repository.OrderRepository;
import com.b.repository.ProductRepository;
import com.b.repository.SeckillActivityRepository;
import com.b.service.OrderService;

import jakarta.annotation.Resource;


@Service
public class OrderServiceImpl implements OrderService{

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private AddressRepository addressRepository;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private ProductRepository productRepository;
    @Resource
    private SeckillActivityRepository seckillActivityRepository;


    @Override
    @Transactional
    public Boolean deleteByPrimaryKey(String id) {
        try {
            Order order = orderRepository.searchById(id);
            if (order == null) {
                System.out.println("订单不存在");
                return false;
            }
            orderMapper.deleteByPrimaryKey(id);
            orderRepository.deleteById(id);
            System.out.println("删除成功");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public int insert(Order record) {
        return orderMapper.insert(record);
    }

    @Override
    public int insertSelective(Order record) {
        return orderMapper.insertSelective(record);
    }

    @Override
    public Order selectByPrimaryKey(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Order record) {
        return orderMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Order record) {
        return orderMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<Order> getAll() {
        return orderMapper.getAll();
    }

    @Override
    public Page<Order> list(Integer userId, Integer productId, String status, PageRequest pageRequest) {
        Page<Order> orders;

        // 根据传入的参数组合进行不同的查询
        if (userId == null && productId == null && (status == null || status.trim().isEmpty())) {
            // 无筛选条件，查询所有
            orders = orderRepository.findAll(pageRequest);
        } else if (userId != null && productId != null && (status == null || status.trim().isEmpty())) {
            // 按用户ID和商品ID筛选
            orders = orderRepository.findByUserIdAndProductId(userId, productId, pageRequest);
        } else if (userId != null && (status == null || status.trim().isEmpty())) {
            // 按用户ID筛选
            orders = orderRepository.findByUserId(userId, pageRequest);
        } else if (productId != null && (status == null || status.trim().isEmpty())) {
            // 按商品ID筛选
            orders = orderRepository.findByProductId(productId, pageRequest);
        } else if ((status != null && !status.trim().isEmpty()) && userId == null && productId == null) {
            // 只按状态筛选
            orders = orderRepository.findByStatus(status.trim(), pageRequest);
        } else if (userId != null && productId != null && (status != null && !status.trim().isEmpty())) {
            // 按用户ID、商品ID和状态筛选
            orders = orderRepository.findByUserIdAndProductIdAndStatus(userId, productId, status.trim(), pageRequest);
        } else if (userId != null && (status != null && !status.trim().isEmpty())) {
            // 按用户ID和状态筛选
            orders = orderRepository.findByUserIdAndStatus(userId, status.trim(), pageRequest);
        } else if (productId != null && (status != null && !status.trim().isEmpty())) {
            // 按商品ID和状态筛选
            orders = orderRepository.findByProductIdAndStatus(productId, status.trim(), pageRequest);
        } else {
            // 默认查询所有
            orders = orderRepository.findAll(pageRequest);
        }

        // 加载地址信息
        orders.getContent().forEach(order -> {
            if (order.getAddressId() != null) {
                addressRepository.findById(order.getAddressId()).ifPresent(order::setAddress);
            }
        });

        return orders;
    }

    @Override
    public Boolean createSeckillOrder(Integer userId, Integer productId, Integer quantity) {
        //创建锁对象
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();

        Boolean lock = ops.setIfAbsent("k1"+userId, "v1");
        if (lock){
            try {
                Long decrement = ops.decrement("stock:" + productId);
                if (decrement >= 0) {
                    // 发送到stock队列的是productId
                    rabbitTemplate.convertAndSend("stock", productId);
                    //根据商品id查询价格
                    Optional<SeckillActivity> seckillActivityOptional = seckillActivityRepository.findByProductId(productId);
                    BigDecimal price = seckillActivityOptional.map(SeckillActivity::getSeckillPrice).orElse(BigDecimal.ZERO);
                    //根据用户id查询用户地址id
                    Optional<Address> addressOptional = addressRepository.findByUserId(userId);
                    Integer addressId = addressOptional.map(Address::getId).orElse(null);
                    // 创建订单对象
                    Order order = new Order();
                    order.setUserId(userId);
                    order.setProductId(productId);
                    order.setAmount(price.multiply(new BigDecimal(quantity)));
                    order.setAddressId(addressId);
                    order.setStatus("待支付");
                    order.setOrderTime(new Date());
                    // 发送到order队列的是订单对象
                    rabbitTemplate.convertAndSend("order", order);
                    System.out.println("发送成功");
                    return true;
                } else {
                    System.out.println("商品已售完");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                //释放锁
                stringRedisTemplate.delete("k1");
            }
        } else {
            System.out.println("锁被占用");
        }
        return false;
    }

    @Override
    @Transactional
    public Boolean createOrder(Integer userId, Integer productId, Integer quantity) {
        try {
            Optional<Product> product = productRepository.findById(productId);
            //根据用户id查地址id
            if (product.isPresent()&&product.get().getStock()>=quantity) {
                //根据用户id查询用户地址id
                Optional<Address> addressOptional = addressRepository.findByUserId(userId);
                Integer addressId = addressOptional.map(Address::getId).orElse(null);
                Order order = new Order();
                order.setUserId(userId);
                order.setProductId( productId);
                order.setAmount(product.get().getPrice().multiply(new BigDecimal(quantity)));
                order.setStatus( "待支付");
                order.setOrderTime( new Date());
                order.setAddressId(addressId);
                orderMapper.insert(order);
                orderRepository.save(order);
                return true;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return false;

    }

    @Override
    @Transactional
    public Boolean updateStatus(String id, String status) {
        try {
            Order order = orderRepository.searchById(id);
            if (order != null) {
                order.setStatus(status);
                orderMapper.updateByPrimaryKey(order);
                orderRepository.save(order);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return false;
    }

    @Override
    public List<Map<String, Object>> getRecent5DaysAmount() {
        LocalDate today = LocalDate.now();
        LocalDate start = today.minusDays(4);
        LocalDate end = today.plusDays(1); // 不包含end

        Date startDate = java.sql.Date.valueOf(start);
        Date endDate = java.sql.Date.valueOf(end);

        // 查询时间范围内的所有订单
        List<Order> orders = orderRepository.findByOrderTimeBetween(startDate, endDate);

        // 按日期分组统计金额
        Map<String, BigDecimal> dayMap = new HashMap<>();
        for (Order order : orders) {
            // 将Date转换为LocalDate
            LocalDate orderDate = order.getOrderTime().toInstant()
                .atZone(java.time.ZoneId.systemDefault())
                .toLocalDate();
            String day = orderDate.toString();
            BigDecimal currentAmount = dayMap.getOrDefault(day, BigDecimal.ZERO);
            dayMap.put(day, currentAmount.add(order.getAmount()));
        }

        // 保证5天都有数据
        List<Map<String, Object>> result = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            LocalDate d = start.plusDays(i);
            String dateStr = d.toString();
            Map<String, Object> map = new HashMap<>();
            map.put("date", dateStr);
            map.put("amount", dayMap.getOrDefault(dateStr, BigDecimal.ZERO));
            result.add(map);
        }
        return result;
    }

}
